package org.dromara.system.controller;

import java.io.File;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.WbItemInfo;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.dto.NoteList;
import org.dromara.system.domain.dto.WbItemInfoGetDTO;
import org.dromara.system.domain.vo.*;
import org.dromara.system.service.*;
import org.dromara.system.utils.HttpClientUtil2;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目
 *
 * @author Lion Li
 * @date 2024-03-22
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/itemInfo")
public class WbItemInfoController extends BaseController {
    private final String PC_DATA="{\"firstPageMenuId\": \"2018032900295987\",\"index\": 1,\"key\": \"\",\"orgId\": \"\",\"orgName\": \"\",\"purOrgCode\": \"\",\"purOrgStatus\": \"\",\"size\":\"100000\" }";

    private final String GJDW_URL="https://ecp.sgcc.com.cn/ecp2.0/ecpwcmcore//index/noteList";

    private final IWbItemInfoService wbItemInfoService;
    private final IWbItemFileService wbItemFileService;
    private final DianWangService dianWangService;

    /**
     * 查询项目列表
     *
     */
    @SaCheckPermission("system:itemInfo:list")
    @GetMapping ("/list")
    public TableDataInfo<WbItemInfoVo> list(WbItemInfoBo bo,PageQuery pageQuery) {
        return wbItemInfoService.queryHdPageList(bo, pageQuery);
    }

    @SaCheckPermission("system:itemInfo:listItemLogs")
    @GetMapping("/listItemLogs")
    public TableDataInfo<WbItemInfoVo> listItemLogs(WbItemInfoBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        return wbItemInfoService.queryListItemLogs(bo,userId, pageQuery);
    }

    @SaCheckPermission("system:itemInfo:getInfo")
    @PostMapping("/getInfo")
    public R getInfo() {
        try {
            List<WbItemInfo> wbItemInfoBos = new ArrayList<>();
            String s = HttpClientUtil2.doPost(GJDW_URL, PC_DATA);
            WbItemInfoGetDTO wbItemInfoGetDTO = JsonUtils.parseObject(s, WbItemInfoGetDTO.class);
            List<NoteList> noteLists = wbItemInfoGetDTO.getResultValue().getNoteList();
            for (NoteList note:noteLists){
                String itemName=note.getPublishOrgName()+note.getTitle();
                String itemId=note.getCode();
                String publishTime = note.getNoticePublishTime();
                WbItemInfo wbItemInfo = new WbItemInfo();
                wbItemInfo.setItemId(itemId);wbItemInfo.setItemName(itemName);wbItemInfo.setPublishTime(publishTime);
                wbItemInfoBos.add(wbItemInfo);
            }
            return wbItemInfoService.insertByBoList(wbItemInfoBos);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 导出项目列表
     */
    @SaCheckPermission("system:itemInfo:export")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WbItemInfoBo bo, HttpServletResponse response) {
        List<WbItemInfoVo> list = wbItemInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "项目", WbItemInfoVo.class, response);
    }



    /**
     * 获取项目详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:itemInfo:query")
    @GetMapping("/{id}")
    public R getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        WbItemInfoVo wbItemInfoVo = wbItemInfoService.queryById(id);

        Map<String,Object> map = new HashMap<>();
        map.put("itemInfo",wbItemInfoVo);

        if("doci-change".equals(wbItemInfoVo.getDocType())){
            WbItemInfoBo wbItemInfoBo = new WbItemInfoBo();
            wbItemInfoBo.setItemId(wbItemInfoVo.getItemId());
            wbItemInfoBo.setDocType("doci-bid");
            List<WbItemInfoVo> list_WbItemInfoVo = wbItemInfoService.queryList(wbItemInfoBo);
            if(list_WbItemInfoVo.size() > 0){
                map.put("itemInfo_online",list_WbItemInfoVo.get(0));
            }
        }

        WbItemFileBo fileBo = new WbItemFileBo();
        fileBo.setItemId(wbItemInfoVo.getId());
        //查询项目文件列表
        List<WbItemFileVo> wbItemFileVos = wbItemFileService.queryList(fileBo);
        List<WbItemFileVo> wbItemFileVoss = new ArrayList<>();
        WbItemFileVo wbItemFileVo = null;
        for (WbItemFileVo vo : wbItemFileVos) {
            if (vo.getUrl().endsWith("zip")) {
                wbItemFileVo = vo;
            } else {
                wbItemFileVoss.add(vo);
            }
        }
        map.put("zipFile", wbItemFileVo);
        map.put("itemFileList",wbItemFileVoss);

        return R.ok(map);
    }

    /**
     * 新增项目
     */
    @SaCheckPermission("system:itemInfo:add")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WbItemInfoBo bo) {
        return toAjax(wbItemInfoService.insertByBo(bo));
    }

    /**
     * 修改项目
     */
    @SaCheckPermission("system:itemInfo:edit")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody WbItemInfoBo bo) {
        return toAjax(wbItemInfoService.updateByBo(bo));
    }

    /**
     * 删除项目
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:itemInfo:remove")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(wbItemInfoService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 批量发布项目
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:itemInfo:edit")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping("/release/{ids}")
    public R<Void> release(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        for (Long id : ids) {
            WbItemInfoVo wbItemInfoVo = wbItemInfoService.queryById(id);
            if("-1".equals(wbItemInfoVo.getStatus())){
                wbItemInfoVo.setStatus("0");
                wbItemInfoService.updateByBo(BeanUtil.toBean(wbItemInfoVo, WbItemInfoBo.class));
            }
        }
        return R.ok();
    }

    /**
     * 批量撤回项目
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:itemInfo:edit")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping("/withdraw/{ids}")
    public R<Void> withdraw(@NotEmpty(message = "主键不能为空")
                           @PathVariable Long[] ids) {
        for (Long id : ids) {
            WbItemInfoVo wbItemInfoVo = wbItemInfoService.queryById(id);
            if(!"-1".equals(wbItemInfoVo.getStatus())){
                wbItemInfoVo.setStatus("-1");
                wbItemInfoService.updateByBo(BeanUtil.toBean(wbItemInfoVo, WbItemInfoBo.class));
            }
        }
        return R.ok();
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @SaCheckPermission("system:itemInfo:edit")
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysOssUploadVo> upload(@RequestPart("file") MultipartFile file,String itemId) {
        if (ObjectUtil.isNull(file) && StringUtils.isEmpty(itemId)) {
            return R.fail("上传文件不能为空且项目ID不能为空");
        }
        if(file.getOriginalFilename().indexOf(".zip") > 0){
            wbItemFileService.deleteByItemId(itemId);
            dianWangService.saveFile(file,itemId);
            return R.ok();
        }
        return R.fail("请上传.zip的压缩文件");
    }
}
